﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Indexes;
using Raven.Abstractions.Data;
using TestPlatform.Performer.RavenDB.Entities;
using TestPlatform.Core;

namespace TestPlatform.Performer.RavenDB
{
    public class RavenDBHelper : IDatabaseHelper
    {
        public static IDocumentStore Store { get; set; }

        static RavenDBHelper()
        {
            Store = new DocumentStore { ConnectionStringName = "RavenDBConnectionString" };
            Store.Initialize();
        }

        public List<Guid> SeedDatabase(int count)
        {
            List<Guid> ids = new List<Guid>();

            using (IDocumentSession s = Store.OpenSession())
            {
                for (int i = 0; i < count; i++)
                {
                    Guid id = Guid.NewGuid();

                    ids.Add(id);
                    s.Store(new User { Id = id, Login = id.ToString(), Name = id.ToString() }, id);
                }

                s.SaveChanges();
            }

            return ids;
        }

        public void ClearDatabase()
        {
            using (IDocumentSession s = Store.OpenSession())
            {
                if (s.Advanced.DocumentStore.DatabaseCommands.GetIndex("RemoveAll") == null)
                {
                    s.Advanced.DocumentStore.DatabaseCommands.PutIndex("RemoveAll", new IndexDefinitionBuilder<User>
                    {
                        Map = documents => documents.Select(entity => new { })
                    }.ToIndexDefinition(new DocumentConvention()));
                }

                s.Advanced.DatabaseCommands.DeleteByIndex("RemoveAll", new IndexQuery(), true);
            }
        }
    }
}
